<?php
/**
 * Class used to organize methods of facebook SDK-PHP
 * @author Edio Hanoway Kepke
 * @version 2.0
 * @access public
 */

class UserFacebook
{                            
    
    private $CI;
    
       
    /**    
    * @name $token
    * @var Object
    */     
    public $token;
    
    
    /**
    * Id facebook user
    * @name $idUserFacebook;
    * @var string
    */     
    public $idUserFacebook;
    
    
    /**
    * id app facebook
    * @name $appId
    * @var string 
    */     
    private $appId = "186307401497770";
    
    
    /**
    * secret key app facebook
    * @name $appsecret
    * @var string 
    */     
    private $appsecret = "1032296604812551f6db043ce7dcae6f";
    
    /**
    * URL this app on facebook
    * @name $appFacebookURL
    * @var string 
    */     
    private $appURL = '';
    
    /**
    * URL this site
    * @name $siteURL
    * @var string 
    */     
    private $siteURL = 'http://toddynho.aquiris.com.br/';   
    
    
    /**
    * A signed_request parameter is POSTed to an application when the app is loaded inside a Canvas page.
    * URL this site
    * @name $signed_request
    * @var Object
    */  
    private $signedRequest;
    
    /**    
    * @name $friends
    * @var Array
    */  
    private $friends;
    
    /**    
    * @name $friendsNotUseApp
    * @var Array
    */  
    private $friendsNotUseApp;
    
    /**    
    * @name $friendsUseApp
    * @var Array
    */  
    private $friendsUseApp;
    
    /**    
    * @name $facebookLib
    * @var Object
    */  
    private $facebookLib;
    
    public function getSignedRequest() { return $this->signedRequest; }
    
    /**
    * Set the acess token
    * @access public
    * @param $token Token caught in facebook
    * @return void
    */        
    public function setToken($token)
    {        
        $this->token = $token;
    }
    
    /**    
    * Init the object user facebook
    * @access public
    * @param $canvasApp boolean is a APP facebook
    * @param $signed_request string
    * @return Object
    */                        
    public function init($canvasApp, $signed_request = null)
    {
        if($canvasApp && !is_null($signed_request))
        {
            $this->setSignedRequest($signed_request);                        
        }
        else
        {
            throw new Exception('Not implement.');            
        }        
    }


    /**    
    * Set this $signed_request
    * @access private
    * @link https://developers.facebook.com/docs/authentication/signed_request/     
    * @return Object     
    */
    private function setSignedRequest($signed_request)     
    {                
        list($encoded_sig, $payload) = explode('.', $signed_request, 2);

        // decode the data
        $sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
        
        $data = json_decode(base64_decode(strtr($payload, '-_', '+/')),true);

        if (strtoupper($data['algorithm']) !== 'HMAC-SHA256')
        {                    
            $this->signedRequest = null;
        }

        // check sig
        $expected_sig = hash_hmac('sha256', $payload, $this->appsecret, $raw = true);
        if ($sig !== $expected_sig) 
        {              
            $this->signedRequest = null;
        }
                
        $this->signedRequest = $data;
    }

    /**    
    * Verifies that the User authorizes the app
    * @access prublic    
    * @return boolean
    */
    public function autorizeAPP()
    {
        if(isset ($this->signedRequest['oauth_token']))
        {
            $this->setToken($this->signedRequest['oauth_token']);
            return true;
        }
        
        return false;
    }           
    
    /**
    * Return object user facebook or false se user no sign or null se user does not have permissions
    * @access public
    * @return Object
    */
    public function getUserInfoFacebook()
    {                                   
        if($this->token)
        {                            
            $graph_url = "https://graph.facebook.com/me?fields=id,first_name,email&access_token=". $this->token;
            
            $response = HelpPost::getCurl($graph_url);
            
            if($response['content']['error']->success)
            {
                return $response['content']['data'];                
            }                         
        }
  
        return false;
    }
    
    
    /**
    * Redirect user to page of authorize permissions 
    * @access public
    * @return Page
    */    
    public function redirectToAuthorizeApp($toSite = false)
    {                                            
        session_start();
        $_SESSION['state'] = md5(uniqid(rand(), TRUE));
        
        if($toSite)
        {            
            $auth_url = "https://www.facebook.com/dialog/oauth?client_id=" . $this->appId . "&redirect_uri=" . urlencode($this->siteURL). "&scope=email,publish_stream&state=".$_SESSION['state'];            
        }
        else 
        {
            $auth_url = "https://www.facebook.com/dialog/oauth?client_id=" . $this->appId . "&redirect_uri=" . urlencode($this->appURL). "&scope=email,publish_stream&state=".$_SESSION['state'];
        }
        
        ?>
            <script type="text/javascript">top.location.href = '<?=$auth_url?>';</script>
        <?php 
    }
    
        
    public function sendMessage($fields, $to)
    {             
        $fields['access_token'] = $this->token;
  
        $url = "https://graph.facebook.com/".$to."/feed?";

        $sendReturn = HelpPost::getCurl($url, $fields, true);                                            
        if($sendReturn['content']['error']->success)
        {
            return true;
        }
                
        $data = array('userid' => $this->idUserFacebook, 'error' => $sendReturn);
                                
        return false;        
    }   
    
    public function readPermission($id)
    {
        $return = HelpPost::getCurl('https://graph.facebook.com/'.$id.'/permissions?access_token='. $this->token);
        
        
        if($return['content']['error']->success)
        {
            $permissions = json_decode($return['content']['data']);
                        
            if(isset ($permissions->data[0]->publish_stream))
            {
                return true;
            }            
        }
        
        return false;
    }
    
        
    public function getListAllFriends()
    {  
        
        $this->friends = $this->getFriends(true);
        $this->friendsUseApp = $this->getFriendsUseApp();
        $this->friendsNotUseApp = $this->getFriendsNotUseApp();
        
        
        if($this->friends && $this->friendsUseApp && $this->friendsNotUseApp)
        {
            return array('all' => $this->friends, 'useapp' => $this->friendsUseApp , 'notuseapp' => $this->friendsNotUseApp);
        }
        
        return false;
    }
    
    public function getFriends($onlyId = false)
    {                   
        $facebook = $this->getFacebookLib();        
                                
        ($onlyId)?($url = '/me/friends&fields=id'):($url = '/me/friends');
                                                                
        try 
        {
            $return = $facebook->api($url);
            
            $this->friends = $return['data'];
            
            $paging = $return['paging'];
            
            while (isset ($paging['next']))
            {
                $return = HelpPost::getCurl($paging['next']);                
                $paging = json_decode($return['content']['data'],true);
                                                                                
                if(!empty ($paging['data']))
                {
                    $this->friends = array_merge($this->friends , $return['data']);
                }
            }
        } 
        catch (Exception $exc) 
        {
            return false;
        }
                      
        if($onlyId)
        {
            $friends = $this->friends;
            $this->friends = array();
            
            foreach ($friends as $friend)
            {
                $this->friends[] = $friend['id'];
            }        
        }
        
        return $this->friends;
    }
    
    public function getFriendsUseApp()
    {                   
        $facebook = $this->getFacebookLib();
        
        $param = array('method' => 'friends.getAppUsers', 'callback' => '');
                
        try 
        {
            $this->friendsUseApp = $facebook->api($param);            
            return $this->friendsUseApp;            
        } 
        catch (Exception $exc) 
        {
            return false;
        }        
    }
    
    public function getFriendsNotUseApp()
    {                
        (isset ($this->friends) && !is_array($this->friends[0])) ?($friends = $this->friends):($friends = $this->getFriends(true));
        
        (isset ($this->friendsUseApp))?($friendsUseApp = $this->friendsUseApp):($friendsUseApp = $this->getFriendsUseApp());
        
        if($friends && $friendsUseApp)
        {
            $this->friendsNotUseApp =  array();                                    
            
            $friendsNotUseApp = array_diff($friends, $friendsUseApp);                                    
            
            foreach ($friendsNotUseApp as $friendNotUseApp) 
            {            
                $this->friendsNotUseApp[] = $friendNotUseApp;
            }
            
            return $this->friendsNotUseApp;
        }
        
        return false;                                
    }
    
    private function getFacebookLib()
    {                
        if(!isset ($this->facebookLib))
        {
            
            $CI =& get_instance();        
            $CI->load->library('facebook', array('appId'  => "422752831082247",'secret' => "4f7691af4dae849174b995a06bc7e983"));
            $CI->facebook->setAccessToken($this->token);
            $this->facebookLib = $CI->facebook;            
        }
                                
        return $this->facebookLib;                
    }

    /**
    * Set session user facebook or redirect to login url
    * @access public
    * @return page or void
    */
    public function getTokenSite()
    {           
        session_start();
        
        if(isset ($_REQUEST["code"]))
        {
            $code = $_REQUEST["code"];
            
            if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) 
            {
                $token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $this->appId . "&redirect_uri=" . urlencode($this->siteURL) . "&client_secret=" . $this->appsecret . "&code=" . $code;

                $response = HelpPost::getCurl($token_url);

                
                if($response['content']['error']->success)
                {                                
                    $params = null;
                    $data = array();
                    $response = parse_str($response['content']['data'], $data);
                    $this->token = $data['access_token'];
                    return $data['access_token'];
                }
            }
        }
        
        return null;
    }    
    
    /**
    * Get the access Token using code provided to facebook
    * @access public
    * @param $code code generated by facebook
    * @return ContentObject
    */    
    private function getAccessToken($code)
    {                                   
        $token_url = "https://graph.facebook.com/oauth/access_token?"."client_id=". $this->appId ."&redirect_uri=" . urlencode($this->appURL) ."&client_secret=". $this->appsecret ."&code=".$code;
        
        $response = HelpPost::getCurl($token_url);
        
        
        
        $params = null;
     
        parse_str($response['content']['data'], $params);
        
        echo Fum::printToDebug($params);
        
        return $params['access_token'];        
    }



}
